﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YunSpace.Application.SiteLibraryManage;
using YunSpace.Domain.ViewModel.StatisticalForm;

namespace YunSpace.Web.Areas.StatisticalForm.Controllers
{
    public class SiteController : ControllerBase
    {
        private readonly SiteApp siteApp = new SiteApp();

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetIndexMapJson()
        {
            var maps = siteApp.GetSiteMaps();
            var data = maps.Select(x => new
            {
                id = x.F_Id,
                name = x.F_FullName.Replace('省', ' ').Trim(),
                value = x.Count
            });

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetIndexBarAndLineDataJson(string provinceId)
        {
            var data = siteApp.GetSiteBarAndLineData(provinceId).OrderBy(x => x.Year).ToArray();
            var names = data.Select(x => x.Name).Distinct().ToArray();
            var nameToIndexMaps = new Dictionary<string, int>();

            for (var i = 0; i < names.Length; i++)
            {
                nameToIndexMaps.Add(names[i], i);
            }

            return Json(new
            {
                names,
                counts = data.GroupBy(x => x.Name).Select(x => x.Sum(y => y.Count)),
                countsOfYear2015 = GetCountsByYear(data, nameToIndexMaps, 2015),
                countsOfYear2016 = GetCountsByYear(data, nameToIndexMaps, 2016),
                countsOfYear2017 = GetCountsByYear(data, nameToIndexMaps, 2017),
                countsOfYear2018 = GetCountsByYear(data, nameToIndexMaps, 2018)
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据年份获取数量
        /// </summary>
        /// <param name="dtos"></param>
        /// <param name="nameToIndexMaps"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        private static int[] GetCountsByYear(IEnumerable<SiteBarDto> dtos, IReadOnlyDictionary<string, int> nameToIndexMaps, int year)
        {
            var list = dtos.Where(x => x.Year == year).ToArray();
            var countsOfYear = new int[nameToIndexMaps.Count];

            foreach (var nameToIndexMap in nameToIndexMaps)
            {
                var name = nameToIndexMap.Key;
                countsOfYear[nameToIndexMaps[name]] =
                    list.Any(x => x.Name == name) ? list.First(x => x.Name == name).Count : 0;
            }

            return countsOfYear;
        }
    }
}